package com.hong.qrpc.listener.impl;

import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.hong.qrpc.Peer;
import com.hong.qrpc.TransportClient;
import com.hong.qrpc.TransportSelector;
import com.hong.qrpc.config.RpcClientConfig;
import com.hong.qrpc.listener.ServerListListener;
import com.hong.qrpc.utils.ReflectionUtils;
import lombok.*;

import java.util.List;

/**
 * 该类用于监听注册中心的服务列表的变化
 *
 * @Author HQT
 * @Date 2022/7/25 9:42
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public class NacosServerListListener implements EventListener, ServerListListener {
    private TransportSelector selector;
    private RpcClientConfig rpcClientConfig;

    @Override
    public void onEvent(Event event) {
        if (event instanceof NamingEvent) {
            List<Instance> instances = ((NamingEvent) event).getInstances();
            for (Instance instance : instances) {
                if (!instance.isHealthy()) {
                    continue;
                }
                Peer peer = new Peer(rpcClientConfig.getProtocolType(), instance.getIp(), instance.getPort());
                TransportClient transportClient = ReflectionUtils.newInstance(rpcClientConfig.getTransportClass());
                //可能会有别的注册中心的提供者，所以这里的服务列表不是全集，不能用来更新，只能用来添加
                selector.appendTransportClient(transportClient, peer);
            }
        }
    }
}
